#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>
#include "log.hpp"
#define BUF_SIZE 1024

class Udpclient
{
public:
    Udpclient(std::uint16_t port, std::string ip)
        : ip_(ip), port_(port), sockfd_(-1)
    {
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            log(FATAL, "create client socket err");
            exit(-1);
        }
        // client不需要手动bind，操作系统会自动bind
    }

    void start()
    {
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_addr.s_addr = inet_addr(ip_.c_str());
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        while (true)
        {
            std::cout<<"Enter# ";
            std::string buffer;
            getline(std::cin,buffer);
            sendto(sockfd_, buffer.c_str(), buffer.size(), 0, (const struct sockaddr *)&local, sizeof(local));
        }
    }

private:
    std::string ip_;
    std::uint16_t port_;
    int sockfd_;
};

int main(int argc,char *argv[])
{
    if(argc == 3)
    {
        Udpclient client(atoi(argv[1]),argv[2]);
        client.start();
    }
    else{
        log(FATAL,"Usage:[%s port ip]",argv[0]);
    }
}